package com.jedi.rabbitmqproducer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.invoke.MethodHandles;

@Configuration
@ConditionalOnProperty(prefix = "spring.rabbitmq", value="host")
public class RabbitmqProducer implements Producer {
    private static final Log logger = LogFactory.getLog(MethodHandles.lookup().lookupClass());

    @Autowired
    private RabbitTemplate template;

    @Override
    public String send(String exchange, String routingKey, Serializable message) {
        ByteArrayOutputStream bout=new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bout);
            oos.writeObject(message);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("write object to stream failed! reason="+e.getMessage());
        }
        try {
            template.send(exchange, routingKey, new org.springframework.amqp.core.Message(bout.toByteArray(), new MessageProperties()));
        }catch (Exception e){
            e.printStackTrace();
            logger.error("send message to queue failed! reason="+e.getMessage());
        }
        return null;
    }
}
